package Z.dailyExercise.April;

import org.omg.CORBA.MARSHAL;

import java.awt.event.KeyEvent;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;

public class _146LRU缓存机制 {
    /**
     * 借助hashmap进行存储 借助双端队列进行优先级的存储 存key
     */
    HashMap<Integer,Integer> map;
    Deque<Integer> deque ;
    int cap;
    public _146LRU缓存机制(int capacity) {
        this.cap = capacity;
        map = new HashMap<>(capacity);
        deque = new ArrayDeque<>();

    }

    public int get(int key) {
        if (map.get(key)!= null){
            deque.remove(key);
            deque.addLast(key);
            return map.get(key);
        }else {
            return -1;
        }

    }

    public void put(int key, int value) {
      //先判断是否有key
        if(map.containsKey(key)){
            //key重复 变数值 删除原来的优先级中的数值 插入新的数值
            map.put(key,value);
            deque.remove(key);
            deque.addLast(key);

        }else {
            //key没有重复 就要判断大小
            if (map.size()<cap){
                map.put(key,value);
                deque.addLast(key);

            }else {
                int rKey = deque.pollFirst();
                map.remove(rKey);
                map.put(key,value);
                deque.addLast(key);
            }
        }

    }
}
